﻿using MySqlConnector;
using System.Data;

namespace DAL
{
    /// <summary>
    /// MySql数据库数据访问通用基类（增删改查CRUD）
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class BaseDAL<T>
    {
        /// <summary>
        /// 通用查询方法
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public virtual DataTable Query(string sql, params MySqlParameter[] parameters)
        {
            return MySqlHelper.ExecuteQuery(sql, parameters);
        }

        /// <summary>
        /// 通用查询单个值的方法
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public virtual object? GetScalar(string sql, params MySqlParameter[] parameters)
        {
            return MySqlHelper.ExecuteScalar(sql, parameters);
        }

        /// <summary>
        /// 通用新增方法
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public virtual int Add(string sql, params MySqlParameter[] parameters)
        {
            return MySqlHelper.ExecuteNonQuery(sql, parameters);
        }

        /// <summary>
        /// 通用新增方法，返回自增ID
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns>自增ID</returns>
        public virtual long AddReturnId(string sql, params MySqlParameter[] parameters)
        {
            return MySqlHelper.ExecuteNonQueryReturId(sql, parameters);
        }

        /// <summary>
        /// 通用修改方法
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public virtual int Update(string sql, params MySqlParameter[] parameters)
        {
            return MySqlHelper.ExecuteNonQuery(sql, parameters);
        }

        /// <summary>
        /// 通用删除方法
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public virtual int Delete(string sql, params MySqlParameter[] parameters)
        {
            return MySqlHelper.ExecuteNonQuery(sql, parameters);
        }

        /// <summary>
        /// 实体转换（转换操作由子类实现）
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        public abstract T ConverToModel(DataRow dr);
    }
}
